<?php

namespace Trawind\Sms;

use Trawind\Helpers\HttpClientHelper;
use Illuminate\Support\Facades\Request;

class Sms
{
    const NOTIFICATION_MICSERVICES_NAME = 'notification';
    const SMS_PATH = 'sms/send';
    const CHECK_PATH = 'sms/check-sms-code';

    public $fullDomain = '';

    public function __construct()
    {
        $this->makeDomain();
    }

    /**
     * make Domain
     */
    protected function makeDomain()
    {
        $appRootUrl = env('APP_ROOT_URL');
        $appEnv = config('app.env');
        $port = Request::getPort();
        // $tenantId = tenant('tenant_id');
        $hostname = Request::getHost();
        $tenantId = explode('.', $hostname)[0];
        if (is_numeric($tenantId)) $tenantStr = $tenantId . '.';
        else $tenantStr = '';
        $this->fullDomain = "{$tenantStr}{$appEnv}." . self::NOTIFICATION_MICSERVICES_NAME . ".{$appRootUrl}" . ($port ? ':' . $port : '') . '/';
    }

    /**
     * send
     *
     * @param string $signName
     * @param string $templateCode
     * @param string $phoneNumber
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function send(string $signName, string $templateCode, string $phoneNumber)
    {
        $uri = $this->fullDomain . self::SMS_PATH;
        $method = 'GET';
        $options = [
            "json" => [
                'sign_name' => $signName,
                'template_code' =>$templateCode,
                'phone_number' => $phoneNumber
            ]
        ];
        $response = HttpClientHelper::factory()->client('user')->request($method, $uri, $options);
        return json_decode($response->getBody(), true);
    }

    /**
     * checkSmsCode
     *
     * @param string $templateCode
     * @param string $phoneNumber
     * @param integer $code
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function checkSmsCode(string $templateCode, string $phoneNumber, int $code)
    {
        $uri = $this->fullDomain . self::CHECK_PATH;
        $method = 'GET';
        $options = [
            "json" => [
                'code' => $code,
                'template_code' =>$templateCode,
                'phone_number' => $phoneNumber
            ]
        ];
        $response = HttpClientHelper::factory()->client('user')->request($method, $uri, $options);
        return json_decode($response->getBody(), true);
    }
}
